package se.webbzon.boltzmann.battle.strategy;

import java.util.Iterator;
import java.util.List;

import se.webbzon.boltzmann.battle.battleaction.BattleAction;
import se.webbzon.boltzmann.battle.battleaction.BattleActionFactory;
import se.webbzon.boltzmann.battle.group.BattleGroup;
import se.webbzon.boltzmann.battle.object.npc.BattleNPC;
import se.webbzon.boltzmann.battle.round.BattleRound;
import se.webbzon.oschi01.worldarea.WorldArea;

public class RandomStrategy extends AbstractStrategy {
	
	// A collection of all battle action factories this strategy can use
	private final List<BattleActionFactory> actions;
	
	// The probability for each action
	private final List<Integer> probabilities;
	
	// The maximal random value
	private final int max;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new random strategy. **/
	public RandomStrategy(	List<BattleActionFactory> actions,
							List<Integer> probabilities) {
		this.actions = actions;
		this.probabilities = probabilities;
		int m = 0;
		for (Integer i : probabilities)
			m += i;
		max = m;
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void onBegin(	BattleRound round, WorldArea world, 
									List<BattleGroup> all, BattleNPC caster) {
		BattleActionFactory actionFactory = selectActionFactory();
		int target = (int) (Math.random()*actionFactory.targets(all,caster));
		BattleAction battleAction = 
				actionFactory.makeBattleAction(	world,
												caster, 
												actionFactory.getTarget(all,caster,target));
		notifyListeners(battleAction);
		battleAction.start();
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Selects an action factory from the list. **/
	private BattleActionFactory selectActionFactory() {
		int choice = (int) (Math.random()*(max+1));
		
		int c = 0;
		BattleActionFactory action = null;
		
		Iterator<Integer> probabilityIterator = probabilities.iterator();
		Iterator<BattleActionFactory> actionIterator = actions.iterator();
		
		while (probabilityIterator.hasNext()) {
			if (choice <= c) {
				action =  actionIterator.next();
				break;
			} else
				c += probabilityIterator.next();
		}
		
		if (action == null)
			action =  actionIterator.next();
		
		return action;
	}

}
